package io.gitee.tziye.core.lock;

import io.gitee.tziye.RenaiClient;
import lombok.Getter;

import java.util.UUID;

public class RenaiLock {

    private final LockOperator lockOperator;

    public final String key;
    public final String value;
    public final int expireSeconds;
    public final Integer timeout;

    @Getter
    private boolean locked;

    public RenaiLock(RenaiClient renaiClient, String key, int expireSeconds, Integer timeout) {
        this.lockOperator = renaiClient.lock();
        this.key = key;
        this.value = UUID.randomUUID().toString();
        this.expireSeconds = expireSeconds;
        this.timeout = timeout;
    }

    public void lock() {
        if (timeout == null) {
            locked = lockOperator.lock(key, value, expireSeconds);
        } else {
            locked = lockOperator.lock(key, value, expireSeconds, timeout);
        }
    }

    public boolean unlock() {
        boolean result = lockOperator.unlock(key, value);
        locked = false;
        return result;
    }

}
